package com.qianbao.qianbaobusiness.ui.start;

import android.Manifest;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;

import com.androidbase.dagger.help.GlideApp;
import com.androidbase.utils.AndroidUtils;
import com.androidbase.utils.ApiLevel;
import com.androidbase.utils.DisplayUtils;
import com.androidbase.utils.FileUtils;
import com.androidbase.utils.RxUtils;
import com.androidbase.utils.StringUtils;
import com.androidbase.utils.ToastUtils;
import com.androidbase.utils.VersionUtils;
import com.baseandroid.MyApplication;
import com.baseandroid.config.Api;
import com.baseandroid.config.Global;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.retrofit.RxObserver;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.CheckUpdate;
import com.qianbao.qianbaobusiness.ui.dialog.UPProgressDialog;
import com.qianbao.qianbaobusiness.ui.dialog.UpdateDialog;
import com.qianbao.qianbaobusiness.ui.guild.GuideActivity;
import com.qianbao.qianbaobusiness.ui.home.HomeActivity;
import com.qianbao.qianbaobusiness.ui.login.LoginActivity;
import com.taobao.sophix.SophixManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.stat.MtaSDkException;
import com.tencent.stat.StatService;
import com.tencent.stat.common.StatConstants;

import java.io.File;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class StartActivity extends BaseMvpActivity<StartView, StartPresent> implements StartView {

    @BindView(R.id.iv_advert_id)
    ImageView iv_advert_id;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;

    private UpdateDialog mUpdataDialog;
    private UPProgressDialog mUpdateProgressDialog;

    private String mDownLoadApkFolde;
    private String mDownLoadApkFileName;

    private ValueAnimator mValueAnimator;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_start_layout;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        DisplayUtils.fullScreen(StartActivity.this, true);
        if (!StringUtils.isEmpty(Global.getAdvertFilePath()) && FileUtils.isExistingFile(new File(Global
                .getAdvertFilePath()))) {
            GlideApp.with(Global.getContext())
                    .load(Global.getAdvertFilePath())
                    .into(iv_advert_id);
            iv_advert_id.setVisibility(View.VISIBLE);
            iv_icon.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        delayShowAnimate();
    }

    private void delayShowAnimate() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                e.onNext("");
                e.onComplete();
            }
        })
                .delay(400, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.newThread())
                .compose(RxUtils.applySchedulersLifeCycle(getMvpView()))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxObserver<Object>() {
                    @Override
                    public void onNext(Object object) {
                        requestAppPermiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        requestAppPermiss();
                    }
                });
        // init
        initMta();
        /*----查询或下载热补丁-----*/
        SophixManager.getInstance().queryAndLoadNewPatch();
    }

    private void initMta() {
        try {
            StatService.startStatService(this, "AEL1U8N1JG8J", StatConstants.VERSION);
        } catch (MtaSDkException e) {
        }
    }

    private void requestAppPermiss() {
        new RxPermissions(StartActivity.this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION)
                .compose(RxUtils.applySchedulersLifeCycle(getMvpView()))
                .subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onComplete() {
                        getPresenter().checkUpdate();
                    }
                });
    }

    @Override
    public void OnVersionUpdate(CheckUpdate checkUpdate) {
        //是否有更新
        final boolean update = VersionUtils.needUpdate(AndroidUtils.getAppVersionName(), checkUpdate
                .getLatest_version(), false);
        final boolean force = VersionUtils.needUpdate(AndroidUtils.getAppVersionName(), checkUpdate
                .getForce_update_version(), true);
        if (update || force) {
            mDownLoadApkFolde = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath();
            mDownLoadApkFileName = "shanghu_" + checkUpdate.getLatest_version() + ".apk";
            mUpdataDialog = new UpdateDialog();
            mUpdataDialog.setCancelable(false);
            mUpdataDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    mUpdataDialog.setContent(checkUpdate.getVersion_desc()
                            .replaceAll("#", "\r\n"));
                    if (update && !force) {
                        // APK可选更新
                        // ...
                    } else if (update && force) {
                        // APK强制更新
                        mUpdataDialog.hideCancelButton();
                    }

                    mUpdataDialog.setConfirmOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mUpdataDialog.dismiss();
                            new RxPermissions(StartActivity.this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                                    .subscribe(new RxObserver<Boolean>() {
                                        @Override
                                        public void onNext(Boolean aBoolean) {
                                            if (aBoolean) {
                                                mUpdateProgressDialog = new UPProgressDialog();
                                                mUpdateProgressDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                                                    @Override
                                                    public void onShow(DialogInterface dialog) {
                                                        getPresenter().requestDownload(Api.sUpdateUrl, mDownLoadApkFolde, mDownLoadApkFileName);
                                                        mUpdateProgressDialog.getDialog()
                                                                .setCanceledOnTouchOutside(false);
                                                    }
                                                });
                                                mUpdateProgressDialog.show(getSupportFragmentManager(), "updateprogressdialog");
                                            } else {
                                                ToastUtils.showShortToast("检查到新版本，但您的权限被拒绝，无法使用存储空间，无法下载最新版本。");
                                            }
                                        }
                                    });
                        }
                    });

                    mUpdataDialog.setCancelOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mUpdataDialog.dismiss();
                            getPresenter().requestUserInfo();
                        }
                    });

                    mUpdataDialog.getDialog().setCanceledOnTouchOutside(false);
                }
            });
            mUpdataDialog.show(getSupportFragmentManager(), "updatadialog");
        } else {
            if (!Global.getFirstUsing()) {
                /*--首次启动进入引导页--*/
                Global.setFirstUsing(true);
                startActivity(new Intent(StartActivity.this, GuideActivity.class));
                finish();
            } else {
                getPresenter().requestUserInfo();
            }
        }
    }

    @Override
    public void OnVersionUpdateError() {
        gotoActivity(LoginActivity.class);
    }

    @Override
    public void OnUserInfoSuccess() {
        gotoActivity(HomeActivity.class);
    }

    @Override
    public void OnUserInfoError() {
        gotoActivity(LoginActivity.class);
    }

    @Override
    public void downloadProgress(int progress) {
        if (mUpdateProgressDialog != null && mUpdateProgressDialog.isVisible()) {
            mUpdateProgressDialog.setProgress(progress);
        }
    }

    @Override
    public void downloadCompleted() {
        if (ApiLevel.requireOreo()) {
            installApp();
        } else {
            AndroidUtils.installApk(new File(mDownLoadApkFolde, mDownLoadApkFileName));
            MyApplication.exitApp();
        }
    }

    private void installApp() {
        @SuppressLint({"NewApi", "LocalSuppress"})
        boolean canbeInstall = AndroidUtils.getContext()
                .getPackageManager()
                .canRequestPackageInstalls();
        if (canbeInstall) {
            AndroidUtils.installApk(new File(mDownLoadApkFolde, mDownLoadApkFileName));
            MyApplication.exitApp();
        } else {
            //请求安装未知应用来源的权限
            new RxPermissions(StartActivity.this).request(Manifest.permission.REQUEST_INSTALL_PACKAGES)
                    .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                    .subscribe(new RxObserver<Boolean>() {
                        @Override
                        public void onNext(Boolean aBoolean) {
                            if (aBoolean) {
                                AndroidUtils.installApk(new File(mDownLoadApkFolde, mDownLoadApkFileName));
                                MyApplication.exitApp();
                            } else {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri
                                        .parse("package:" + getPackageName()));
                                startActivityForResult(intent, 0x0800);
                            }
                        }
                    });
        }
    }

    @Override
    public void downloadFailed() {
        ToastUtils.showLongToast(R.string.start_file_download_error);
        if (mUpdateProgressDialog != null && mUpdateProgressDialog.isVisible()) {
            mUpdateProgressDialog.dismiss();
        }

        gotoActivity(LoginActivity.class);
    }

    private void gotoActivity(final Class classzz) {
        mValueAnimator = ValueAnimator.ofFloat(1.0f, 0.9f);
        mValueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (classzz.getSimpleName()
                        .equals(HomeActivity.class.getSimpleName()) && getIntent().getBundleExtra("pushIntent") != null) {
                    //判断是否推送进来的
                    Intent intent = new Intent(StartActivity.this, classzz);
                    intent.putExtra("pushIntent", getIntent().getBundleExtra("pushIntent"));
                    startActivity(intent);
                } else {
                    startActivity(new Intent(StartActivity.this, classzz));
                }
                finish();
                overridePendingTransition(R.anim.face_in, R.anim.face_out);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                getWindow().getDecorView().getRootView().setAlpha(alpha);
            }
        });

        mValueAnimator.setDuration(800);
        mValueAnimator.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == 0x0800) {
            installApp();
        } else if (resultCode == RESULT_CANCELED && requestCode == 0x0800) {
            MyApplication.exitApp();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mValueAnimator != null) {
            mValueAnimator.removeAllUpdateListeners();
            mValueAnimator.cancel();
        }
    }

}
